package com.likerSai;

/**
 * 最长公共前缀
 *
 * @author sun.ye
 * @since 2021-06-16 20:21
 */
public class LongestCommonPrefix {

    public static void main(String[] args) {
        String[] strs = new String[]{"flower","flower","flower","flower"};
        String s = longestCommonPrefix(strs);
        System.out.println(s);
    }


    public static String longestCommonPrefix(String[] strs){
        if (strs.length == 0){
            return "";
        }else if (strs.length == 1){
            return strs[0];
        }else if (strs[0].length() == 0){
            return "";
        }
        StringBuilder sb = new StringBuilder();
        boolean endFlag = false;
        int i = 0;
        while (!endFlag){
            if (strs[0].length() <= i){
                endFlag =true;
                break;
            }
            char c = strs[0].charAt(i);
            for (int j = 1 ; j < strs.length; j++){
                if (strs[j].length() <= i){
                    endFlag =true;
                    break;
                }
                if (strs[j].charAt(i) != c){
                    endFlag =true;
                    break;
                }
            }
            if (!endFlag){
                sb.append(c);
            }
            i++;
        }
        return sb.toString();
    }


}